<template>
  <div class="product-detail">
    <el-row :gutter="20">
      <el-col :span="12">
        <button @click="goBack" class="back-button" icon="el-icon-arrow-left">返回</button>
        <!-- 产品图片轮播 -->
        <el-carousel height="600px"> <!-- 设置合适的固定高度 -->
          <el-carousel-item v-for="img in product.imageUrl" :key="img">
            <div class="image-container">
              <img :src="img" alt="Product image" class="product-image" />
            </div>
          </el-carousel-item>
      </el-carousel>
      </el-col>
      <el-col :span="12">
        <!-- 产品详细信息 -->
        <div class="product-info">
          <h2>{{ product.name }}</h2>
          <p class="product-description">{{ product.description }}</p>
          <ul class="product-specs" style="list-style-type: none;">
            <li v-for="(value, key) in product.specs" :key="key" class="spec-item">{{ key }}: {{ value }}</li>
          </ul>
          <el-button type="primary" @click="addToCart" style="margin-right: 20px;">添加到购物车</el-button>
          <router-link to="/cart" class="cart-link">查看购物车</router-link>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { useCartStore } from '../stores/cartStore';
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();

// 定义产品数据
const product = ref({});

// 获取产品详细数据的函数
const fetchProductDetail = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/api/product/getProductById?id=${route.params.id}`);
    const products = response.data;
    // 确保 imageUrl 是数组，如果是字符串则转为数组
    products.imageUrl = Array.isArray(products.imageUrl) 
      ? products.imageUrl 
      : products.imageUrl.split('，').map(img => `/src${img.substring(2)}`); // 使用中文逗号分隔

    // 处理 specs 字符串，将其转换为对象
    let specsStr = products.specs;
    specsStr = specsStr.replace(/“/g, '"').replace(/”/g, '"').replace(/：/g, ':').replace(/，/g, ',');
    try {
      products.specs = convertSpecsStringToObject(specsStr);
    } catch (parseError) {
      console.error("解析 specs 字符串失败:", parseError);
      products.specs = {};
    }
    product.value = products;
    console.log(product.value.imageUrl);
  } catch (error) {
    console.error("获取产品详情失败:", error);
  }
};

// 转换 specs 字符串为对象的函数
const convertSpecsStringToObject = (specsStr) => {
  const specs = {};
  specsStr.split(',').forEach(pair => {
    const [key, value] = pair.split(':').map(s => s.trim());
    if (key && value) {
      const cleanKey = key.replace(/"/g, '');
      const cleanValue = value.replace(/"/g, '');
      specs[cleanKey] = cleanValue;
    }
  });
  return specs;
};

onMounted(async () => {
  await fetchProductDetail();
});

const goBack = () => {
  window.history.back();  // 使用浏览器的历史记录返回上一页
};

// 添加到购物车
const cartStore = useCartStore();
const addToCart = () => {
  cartStore.addItem({
    id: product.value.id,
    name: product.value.name,
    price: product.value.price,
    quantity: 1,
    imageUrl: product.value.imageUrl
  });
};
</script>

<style>
.product-detail {
  margin-top: 15px;
}

.product-image {
  width: 100%;
  height: auto;
  max-width: 500px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  /* 添加以下属性 */
  image-rendering: -webkit-optimize-contrast; /* Chrome和Safari */
  image-rendering: crisp-edges; /* Firefox */
  -ms-interpolation-mode: nearest-neighbor; /* IE */
}

.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  overflow: hidden;
}

.product-info {
  margin-top: 100px;
  padding: 20px;
}

.product-description {
  margin-bottom: 20px;
  font-size: 1.1em;
  line-height: 1.5;
  color: #444;
}

.product-specs {
  margin-bottom: 20px;
  line-height: 1.6;
  list-style-type: none;
  padding: 0;
}

.spec-item {
  margin-bottom: 10px;
}

.cart-link {
  margin-top: 15px;
  display: inline-block;
  color: #409EFF;
}

.back-button {
  position: absolute;
  width: 80px;
  height: 40px;
  left: 20px;
  z-index: 10;
  font-size: 20px;
  color: white;
  border-radius: 10%;
  border: skyblue;
  background-color: skyblue;
}
</style>
